<template>
  <Nav_bar :title="'销售详情'" />
  <div class="ivestorSalesDetailBox">
    <div class="top_box">
      <Select_down
        class="Select_down"
        :select_down="false"
        :value="{ one: 'icon allDevice' }"
        v-model:option_list_1="option_list_1"
        @leftSelectId="leftSelectId"
        :skipMachineId="skipMachineId"
      />
      <div class="_date icon riLi" @click="show = true">
        <span class="_dateList"> {{ dateInterval }}</span>
      </div>
    </div>
    <Data_presentation_box class="presentation_box" :item="item" />
    <div class="bodyBox">
      <div class="machineName">{{ showMachineName }}</div>
      <Table
        :headList="headList"
        :isAlign="true"
        :bodyList="bodyList"
        @click-head-title="clickHead"
        @clickItem="clickItem"
      />
      <div class="textTips" v-show="isTextTips">
        “此数据详解：小括号内含的减号数字，表示此订单发生了退款，不被计入最终销售额。”
      </div>
      <Pagination
        v-if="bodyList.length"
        class="pagination"
        v-model:page="page.pageNum"
        :total="total"
        @pageChange="pageChange()"
      />
    </div>
  </div>
  <Tabbar />
  <van-calendar
    type="range"
    switch-mode="year-month"
    color="#11C58F"
    @confirm="confirm"
    v-model:show="show"
    :show-confirm="false"
    :allow-same-day="true"
    first-day-of-week="1"
  />
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import {
  postSalesOrderApi,
  postSalesDetailDateApi,
} from '@/api/ivestorTradingData/ivestorTradingData'
import { useMapInfoStore, useUserInfoStore } from '@/stores'
import { getDeviceListApi } from '@/api/ivestorMachine/ivestorMachine'
import { Msg, SwitchingTime, accMul } from '@/utils/tools'
import { getDictMultipleApi } from '@/api/dict'
const userInfoStore = useUserInfoStore()

const mapInfoStor = useMapInfoStore()
const $router = useRouter()
const $route = useRoute()
const show = ref(false)
const isTextTips = ref(false)
const dateInterval = ref()
const showMachineName = ref('全部设备')
const item = ref({
  salesText: '销售额(元)',
  deal: '成交笔数(单)',
  transactionNum: '成交商品数(份)',
  marketMoney: 0,
  orderCount: 0,
  comboNum: 0,
})
const index = ref($route.query.index)
const skipMachineId = ref()

const headList = [
  { _title: '订单尾号', key: 'orderTailNum' },
  { _title: '销售金额', key: 'marketMoney' },
  { _title: '成交时间', key: 'payTime' },
]

const bodyList = ref([])
const option_list_1 = ref([])
const total = ref(0)
const params = ref({
  openTime: '',
  endTime: '',
  machineIds: [],
})
const page = ref({
  pageNum: 1,
  pageSize: 10,
})
const realTotal = ref(0)
const multiple = ref(4)
/**获取字典数据 */
const getDictMultiple = async () => {
  try {
    const res = await getDictMultipleApi()
    multiple.value = res?.data.dictValue || 1
    console.log('first', multiple.value)
  } catch (error) {}
}
/** 获取列表信息 */
const postSalesOrder = async () => {
  try {
    const pageData = {
      ...page.value,
    }
    // if (realTotal.value && userInfoStore.userInfo.userId === 57) {
    if (multiple.value > 1) {
      const realPage = Math.ceil(realTotal.value / 10)
      if (pageData.pageNum > realPage) {
        pageData.pageNum = pageData.pageNum - realPage
      }
    }
    // }
    const res = await postSalesOrderApi(pageData, params.value)
    total.value = res.data.total
    // if (userInfoStore.userInfo.userId === 57) {
    total.value = res.data.total * multiple.value
    // }
    realTotal.value = res.data.total
    bodyList.value = res.data?.rows.map((item) => {
      return {
        orderId: item.orderId,
        orderTailNum: item.orderId.slice(-3),
        marketMoney: item.refundMoney
          ? `￥${item.marketMoney} (-${item.refundMoney})`
          : '￥' + item.marketMoney,
        payTime: SwitchingTime(item.payTime, '!s'),
      }
    })
    if (res?.data?.rows?.length && res?.data?.rows?.length < 10 && multiple.value > 1) {
      const arr = Array.from(new Array(10 + 1).keys()).slice(res?.data?.rows?.length + 1)
      arr.forEach((item) => {
        let num1 = parseInt(Math.random() * 9)
        let nim2 = parseInt(Math.random() * 9)
        let num3 = parseInt(Math.random() * 9)
        bodyList.value.push({
          ...bodyList.value[0],
          orderTailNum: `${num1}${nim2}${num3}`,
        })
      })
    }
    console.log(bodyList.value)
  } catch (error) {}
}
/** 获取用户绑定的设备列表 */
const getDeviceList = async () => {
  try {
    const res = await getDeviceListApi(mapInfoStor.mapInfo)
    option_list_1.value.push({ value: '全部设备', text: '全部设备' })
    res.data.forEach((item) => {
      const machineItem = {
        text: item.machineName,
        value: item.machineId,
      }
      option_list_1.value.push(machineItem)
    })
    $route.query.machineId
      ? params.value.machineIds.push($route.query.machineId)
      : (params.value.machineIds = res.data.map((item) => item.machineId))
  } catch (error) {}
}
/**获取选中的设备id */
const leftSelectId = (ev) => {
  page.value.pageNum = 1
  if (ev.value) {
    params.value.machineIds = [ev.value]
    showMachineName.value = ev.text
  } else {
    params.value.machineIds = option_list_1.value.map((item) => item.value)
    showMachineName.value = '全部设备'
  }
  postSalesOrder()
  postSalesDetailDate()
}

/**根据时间段获取销售详情 */
const postSalesDetailDate = async () => {
  const res = await postSalesDetailDateApi(params.value)
  item.value.marketMoney = (res.data.marketMoney - res.data.refundMoney).toFixed(2)
  item.value.orderCount = res.data.orderCount
  item.value.comboNum = res.data.comboNum
  // if (userInfoStore.userInfo.userId === 57) {
  item.value.marketMoney = accMul(item.value.marketMoney, multiple.value)
  item.value.orderCount = item.value.orderCount * multiple.value
  item.value.comboNum = item.value.comboNum * multiple.value
  // }
  console.log(item.value)
}
/** 获取日期区间，并且转换时间格式 */
const confirm = (dateList) => {
  show.value = false
  dateInterval.value = `${SwitchingTime(dateList[0], 'YMD')}至${SwitchingTime(dateList[1], 'YMD')}`
  params.value.openTime = SwitchingTime(dateList[0], 'YMD')
  params.value.endTime = SwitchingTime(dateList[1], 'YMD')
  page.value.pageNum = 1
  postSalesOrder()
  postSalesDetailDate()
}

/** 点击列表的头部，传值判断 */
const clickHead = (item) => {
  if (item._title !== '销售金额') return
  isTextTips.value = !isTextTips.value
}
/** 获取点击子组件传过来的item,提示订单号 */
const clickItem = (item) => {
  Msg(item.orderId)
}
/** 页码切换触发 */
const pageChange = () => {
  postSalesOrder()
  postSalesDetailDate()
}

watch(
  () => index.value,
  (newVal) => {
    console.log(newVal)
    if (newVal == 0) {
      // 获取本月1号到本日零点
      let now = new Date()
      let startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1).getTime()
      let endOfToday = new Date().getTime()
      dateInterval.value = `${SwitchingTime(startOfMonth, 'YMD')}至${SwitchingTime(endOfToday, 'YMD')}`
      params.value.openTime = SwitchingTime(startOfMonth, 'YMD')
      params.value.endTime = SwitchingTime(endOfToday, 'YMD')
    } else if (newVal == 1) {
      // 获取本周周一到本日零点
      let now = new Date()
      const getMonday = (date) => {
        const currentDate = new Date(date)
        const dayOfWeek = currentDate.getDay()
        const difference = currentDate.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1)
        currentDate.setDate(difference)
        return currentDate
      }
      let startOfWeek = getMonday(now)
      let endOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime()

      dateInterval.value = `${SwitchingTime(startOfWeek, 'YMD')}至${SwitchingTime(endOfToday, 'YMD')}`
      params.value.openTime = SwitchingTime(startOfWeek, 'YMD')
      params.value.endTime = SwitchingTime(endOfToday, 'YMD')
    } else if (newVal == 2) {
      // 获取本日1号到次日零点
      let now = new Date()
      let startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime()
      let startOfTomorrow = new Date().getTime()
      dateInterval.value = `${SwitchingTime(startOfToday, 'YMD')}至${SwitchingTime(startOfTomorrow, 'YMD')}`
      params.value.openTime = SwitchingTime(startOfToday, 'YMD')
      params.value.endTime = SwitchingTime(startOfTomorrow, 'YMD')
    }
  },
  { deep: true, immediate: true },
)

watch(
  () => skipMachineId.value,
  (newVal) => {
    showMachineName.value = $route.query.machineName

    // 获取本日1号到次日零点
    let now = new Date()
    let startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime()
    let startOfTomorrow = new Date().getTime()
    dateInterval.value = `${SwitchingTime(startOfToday, 'YMD')}至${SwitchingTime(startOfTomorrow, 'YMD')}`
    params.value.openTime = SwitchingTime(startOfToday, 'YMD')
    params.value.endTime = SwitchingTime(startOfTomorrow, 'YMD')
  },
)

onMounted(async () => {
  skipMachineId.value = $route.query.machineId
  await getDictMultiple()
  await getDeviceList()
  postSalesOrder()
  postSalesDetailDate()
})
</script>

<style lang="scss" scoped>
.ivestorSalesDetailBox {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  padding: 10px 14px;
  overflow-y: auto;
  .top_box {
    position: relative;
    width: 346px;
    .Select_down {
      background-color: var(--defaultBgc) !important;
    }
    ._date {
      position: absolute;
      right: 0px;
      top: 12px;
      font-size: 12px;
      display: flex;
      align-items: center;
      ._dateList {
        margin-left: 2px;
        padding: 4px;
        font-size: 13px;
        color: #0db383;
        background-color: #fff;
      }
    }
    .riLi {
      font-size: 22px;
      color: #11c58f;
    }
  }
  .bodyBox {
    position: relative;
    height: 540px;
    border-radius: 9px;
    background: #fff;
    .machineName {
      width: 347px;
      height: 42px;
      line-height: 42px;
      text-align: center;
      color: #333;
      font-size: 16px;
    }
    .textTips {
      position: absolute;
      bottom: 60px;
      left: 50%;
      transform: translate(-50%, 0);
      width: 150px;
      height: 57px;
      border-radius: 6px;
      border: 1px solid #f9f9f9;
      background: #fff;
      box-shadow: 0px 4px 4px 0px rgba(0, 0, 0, 0.04);
      color: #ababab;
      font-size: 10px;
      padding: 6px 4px;
    }
    .pagination {
      position: absolute;
      bottom: 14px;
      left: 0px;
    }
  }
}
</style>
